import React from 'react';
import {TreeData} from './data'
import file from '../../assets/file.png'
import closedFolder from '../../assets/closed-folder.png'
import openedFolder from '../../assets/opened-folder.png'
import loadingSrc from '../../assets/loading.gif'
interface Props{
    data:TreeData
    onCollapse?:any
    onCheck?:any
    checked?:any 
}


const TreeNode:React.FC<Props> = (props) =>{
    let {data:{name,children,key,collapsed,checked,loading},onCheck} = props
    let caret = null;//默认为null,打开关闭的小箭头
    let icon = null; //图标
    if(children){//如果children有值
        if(children.length>0){
             caret=(
                <span 
                    className={`collapse ${collapsed?"caret-right":"caret-down"}`}
                    onClick={()=>props.onCollapse(key)}
            ></span>
             )
             icon = collapsed?closedFolder:openedFolder
        }else{
            caret = null;
            icon = file
        }
    }else{
        caret = (
            loading?<img src={loadingSrc} style={{width:14,top:'50%',marginTop:-7}} className="collapse"/>:
            <span 
                    className={`collapse caret-right`}
                    onClick={()=>props.onCollapse(key)}
            ></span>
        )
        icon = closedFolder;//关闭的文件夹
    }
    return (
        <div className="treeNode">
            <div className="inner">
                {caret}
                <span className="content">
                    <input type="checkbox" checked={checked} onChange={()=>onCheck(key)}/>
                    <img style={{width:20}} src={icon}></img>
                    {name}
                </span>
            </div>
            {
                //有儿子去迭代
                (children && children.length > 0  && !collapsed)&&(
                    <div className='children'>
                        {
                            children.map((item:TreeData)=>
                                <TreeNode 
                                    data={item} 
                                    key={item.key} 
                                    onCollapse={props.onCollapse} 
                                    onCheck={onCheck}
                                />
                            )
                        }
                    </div>
                )
            }
        </div>
    )
}

export default TreeNode